﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using InnovTech.Persistence;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;

namespace InnovTech.Persistence
{
    public abstract class NHDatabaseGeneratorBase<TDataInfo> : IDatabaseGenerator<TDataInfo>
        where TDataInfo : INHDatabaseInfo
    {

        ISessionFactoryBuilder<TDataInfo> _sessionFactoryBuilder;
        Configuration _config;
        string _connectionString;


        public NHDatabaseGeneratorBase(ISessionFactoryBuilder<TDataInfo> builder)
        {
            _sessionFactoryBuilder = builder;
        }

        protected abstract void CreateEmptyDatabase(string connectionStr);

        protected void ImportDatabaseSchema(Configuration config)
        {
            SchemaExport export = new SchemaExport(config);
            export.Create(false, true);
        }

        public TDataInfo GenerateDatabase()
        {
            Initialize();
            CreateEmptyDatabase(_connectionString);
            ImportDatabaseSchema(_config);
            return _sessionFactoryBuilder.DatabaseInfo;
        }


        private void Initialize()
        {
            _config = _sessionFactoryBuilder.BuildConfiguration();
            _connectionString = _config.GetProperty(NHibernate.Cfg.Environment.ConnectionString);
        }
    }
}
